package com.retrofit.library;

import com.retrofit.library.callback.RespCallback;
import com.retrofit.library.converter.JsonConverterFactory;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * Desc:
 * Date:   2017/9/8 0008 15:12
 */

public class RetrofitUtils {
    private String TAG = this.getClass().getName();
    private static volatile RetrofitUtils mInstance;

    private static Retrofit mRetrofit;
    private static ApiService apiService;
    //超时时间
    private static final int TIMEOUT = 1000 * 5;
    //json 请求
    private static final MediaType JSON = MediaType.parse("application/json;charset=utf-8");
    private static final MediaType MARKDOWN = MediaType.parse("text/x-markdown; charset=utf-8");

    private String headerToken;

    /**
     * OkHttpClient 全局配置
     */
    public void init(String baseUrl) {
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .sslSocketFactory(SSL.defaultSocketFactory(), SSL.defaultTrustManager())
                .hostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                })
                .readTimeout(TIMEOUT, TimeUnit.MILLISECONDS)
                .connectTimeout(TIMEOUT, TimeUnit.MILLISECONDS)
                .writeTimeout(TIMEOUT, TimeUnit.MILLISECONDS)
                .build();
        mRetrofit = new Retrofit.Builder()
                .client(okHttpClient)
                .baseUrl(baseUrl)
                .addConverterFactory(ScalarsConverterFactory.create())
//                .addConverterFactory(GsonConverterFactory.create())
                .addConverterFactory(JsonConverterFactory.create()) // 与 Gson 互斥
                .build();

        apiService = mRetrofit.create(ApiService.class);
    }

    public static RetrofitUtils getInstance() {
        if (mInstance == null) {
            synchronized (RetrofitUtils.class) {
                if (mInstance == null) {
                    mInstance = new RetrofitUtils();
                }
            }
        }
        return mInstance;
    }


    /**
     * post 请求
     *
     * @param path     相对路径
     * @param params   请求参数
     * @param callback 请求回调
     */
    public Call<String> post(String path, Map<String, Object> params,
                             RespCallback<String> callback) {
        //        Call<String> call = apiService.post(path, params);
        RequestBody body = postWithJson(params);
        Call<String> call = apiService.post(path, headerToken, body);
        call.enqueue(callback);
        return call;
    }


    public RequestBody postWithJson(Map<String, Object> params) {
        if (params != null && !params.isEmpty() && params.containsKey("loginToken")) {
            headerToken = (String) params.get("loginToken");
            // 参数里面移除params
            params.remove("loginToken");
        }

        String jsonFormat = JsonUtils.toJson(params);
        return RequestBody.create(JSON, jsonFormat);
    }


    public void cancelRequst(Call call) {
        if (call != null && !call.isCanceled())
            call.cancel();
    }


    public static Retrofit getRetrofit() {
        return mRetrofit;
    }

    public String getHeaderToken() {
        return headerToken;
    }
}
